//Author: Matthias Heisler

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int calcPi(int iterations, double * erg);

int main(int argc,char **argv)
{
    int iterations = 0;
    long runtime = 0;
    double result = 0.0;

    if(argc != 2){
        printf("Error: Missing argument. Please enter the amount of iterations to calculate pi.\n");
        return -1;
    }

    iterations = atoi(argv[1]);

    runtime = calcPi(iterations,&result);
    printf("%d %ld %lf\n",iterations,runtime,result);

    return 0;
}

int calcPi(int iterations, double *result){
    struct timeval start, end;
    double erg = 0;
    int i = 0;
    double xi = 0;
    double deltaX = 1.0/iterations;

    //determine start time
    gettimeofday(&start,NULL);

    for(i = 0;i < iterations;i++){
        xi = (double)i/(double)iterations;
        erg = erg + (4.0/(1.0 + xi*xi))*deltaX;
    }

    //determine end time
    gettimeofday(&end,NULL);

    *result = erg;
    return (end.tv_sec - start.tv_sec)*1000000+end.tv_usec-start.tv_usec;
}
